package com.cc.service.supply;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.List;
import java.util.stream.Collectors;

import com.cc.infrastructure.inter.supply.SupplyInter;
import com.cc.web.vo.SupplyVo;
import com.cc.infrastructure.db.SupplyDb;
import com.cc.pojo.dto.SupplyDto;
import com.cc.infrastructure.special.dto.SupplyDo;

/**
 * @author C.c
 **/
@Service
public class SupplyService {
  @Resource
  private SupplyInter supplyInter;

  /**
   * 分页
   *
   * @author C.c
   **/
  public Page<SupplyVo> query(String name, int pageNum, int pageSize) {
    Page<SupplyDo> supplyDoDos = supplyInter.query(name, pageNum, pageSize);
    List<SupplyVo> collect = supplyDoDos.stream().map(SupplyVo::convertSupplyVoBySupplyDo).collect(Collectors.toList());
    return new PageImpl<>(collect, supplyDoDos.getPageable(), supplyDoDos.getTotalElements());
  }

  /**
   * 新增
   *
   * @author C.c
   **/
  @Transactional(rollbackFor = Exception.class)
  public boolean add(SupplyDto supplyDto) {
    SupplyDb supplydb = SupplyDto.convertSupplyDbBySupplyDto(supplyDto);
    supplydb.setId(UUID.randomUUID().toString());
    supplyInter.save(supplydb);
    return true;
  }

  /**
   * 删除
   *
   * @param id
   * @return boolean
   * @author C.c
   **/
  public boolean delete(String id) {
    supplyInter.deleteById(id);
    return true;
  }

  /**
   * 修改
   *
   * @return boolean
   * @author C.c
   **/
  @Transactional(rollbackFor = Exception.class)
  public boolean edit(SupplyDto supplyDto) {
    SupplyDb supplydb = SupplyDto.convertSupplyDbBySupplyDto(supplyDto);
    supplyInter.save(supplydb);
    return true;
  }

  /**
   * 查询单个
   *
   * @param id 唯一标识
   * @author C.c
   **/
  public SupplyVo view(String id) {
    SupplyDb supplydb = supplyInter.findById(id).orElse(null);
    return SupplyVo.convertSupplyVoBySupplyDo(supplydb);
  }
}